<?php
// +----------------------------------------------------------------------
// | IPHP
// +----------------------------------------------------------------------
// | This is an open source and simple PHP FrameWork.
// +----------------------------------------------------------------------
// | $Id$
// +----------------------------------------------------------------------


/**
 * 引入类库的函数
 * @param string $class 类库命名空间字符串
 * @param string $baseUrl 起始路径
 * @param string $ext 导入的文件扩展名
 * @return boolean
 */
function import($class, $baseUrl = '', $ext = CLASS_EXT) {
    static $_file = array();

    // TODO: 自动导入功能还需要重构

    $class = str_replace(array('.', '#'), array('/', '.'), $class);
    $class = str_replace('\\', '/', $class);
    if (isset($_file[$class . $baseUrl])){
        return true;
    } else {
        $_file[$class . $baseUrl] = true;
    }
    
    $class_strut = explode('/', $class);

    if (empty($baseUrl)) {
        if ($class_strut[0] == 'IPHP') {
            // 框架内的类命名空间
            $baseUrl = IPHP_PATH;

            $class = str_replace('IPHP/', '', $class);

        }else {
            // 加载其他模块的类库
            $baseUrl = APP_PATH;
            if($class_strut[1] == "Lib") {
                $class = str_replace('App/', '', $class);
            } else {
                $class = str_replace('App/', MODULE_NAME.'/', $class);
            }

            
        }
    }
    if (substr($baseUrl, -1) != '/')
        $baseUrl    .= '/';

    $classFile = $baseUrl.$class.$ext;
    include_once $classFile;
    
}

/**
 * var_dump()
 * @param  [type]  $var  [description]
 * @param  boolean $echo [description]
 * @return [type]        [description]
 */
function dump($var, $echo=true) {
    ob_start();
    var_dump($var);
    $output = ob_get_clean();
    $output = preg_replace('/\]\=\>\n(\s+)/m', '] => ', $output);
    $output = htmlspecialchars($output, ENT_QUOTES);

    if($echo) {
        echo '<pre>'.$output.'</pre>';
    } else {
        return $output;
    }
}

/**
 * 设置与获取配置
 * @return [type] [description]
 */
function config() {
    global $config;
    include_once CONF_PATH.'config.php';
    $argarr = func_get_args();
    if(func_num_args() == 0) {
        return $config;
    } elseif(func_num_args() == 1) {
        return $config[$argarr[0]];
    } elseif(func_num_args() > 1) {
        $config[$argarr[0]] = $argarr[1];

        // 重新将新的配置写入到文件
        $file = CONF_PATH.'config.php';
        $f = fopen($file,"w+");
        fwrite($f, '<?php'."\r\n");
        fwrite($f, '// +----------------------------------------------------------------------'." \r\n");
        fwrite($f, '// * 系统配置文件'."\r\n");
        fwrite($f, '// +----------------------------------------------------------------------'." \r\n");
        fwrite($f, "\r\n");
        fwrite($f, "\r\n");

        fwrite($f, '!defined(\'IN_IPHP\') && exit(\'Access Denied\');'."\r\n");
        fwrite($f, "\r\n");
        fwrite($f, "\r\n");

        writeconfig($f,$config);
        fclose($f);
        return true;
    }
}

/**
 * 将数组写入到文件中
 * @param  [type] $f      [description]
 * @param  [type] $config [description]
 * @return [type]         [description]
 */
function writeconfig($f,$config) {
    if(!is_array($config)) return false;
    foreach ($config as $key => $val) {
        //如果参数是数组,并且只支持二维数组
        if(is_array($val)) {
            fwrite($f, '$config[\''.$key.'\'] = array('."\r\n");

                foreach ($val as $k => $v) {
                    if(empty($k) || empty($v)) continue;
                    if($v === false) {
                        $v = 'false';
                        fwrite($f, '\''.$key.'\' => '.$v.','."\r\n");
                    } else if (is_numeric($v)) {
                        fwrite($f, '\''.$key.'\' => '.$v.','."\r\n");
                    } else {
                        fwrite($f, '\''.$key.'\'] => \''.$v.'\','."\r\n");
                    }
                }

            fwrite($f, ');'."\r\n");
        } else {
            if($val === false) {
                $val = 'false';
                fwrite($f, '$config[\''.$key.'\'] = '.$val.';'."\r\n");
            } else if (is_numeric($val)) {
                fwrite($f, '$config[\''.$key.'\'] = '.$val.';'."\r\n");
            } else {
                fwrite($f, '$config[\''.$key.'\'] = \''.$val.'\';'."\r\n");
            }
        }
    }
}

/**
 * 返回日志文件路径
 * @return [type] [description]
 */
function getLogPath() {
    $path = ROOT_PATH."Cache/Logs/";
    if(!is_dir($path)) {
        mkdir($path,0777,1);
    }
    return $path;
}


/**
 * 生成url地址
 * 暂时还不支持路由模式，只有pathinfo 
 * 默认后缀.html
 */
function url($path='',$args="", $showshuffix= false) {
    //TODO: 还需要支持路由功能
    $url = __ROOT__.'/index.php/'.$path;
    $a = '';
    if($args) {
        $arr = explode('&', $args);
        if(is_array($arr)) {
            foreach ($arr as $key => $val) {
                $arg = explode('=', $val);
                $a .= implode('/', $arg);
                $a .= '/';
            }
        }
        $url = $url.'/'.rtrim($a,'/');
    }

    if($showshuffix) $url .= '.html';
    return $url;
}


/**
 * 数据安全过滤
 * @param  [type] $value [description]
 * @return [type]        [description]
 */
function checkSql($value) {
    // $check　=　eregi('select|insert|update|delete|\'|\/\*|\*|\.\.\/|\.\/|union  |into|load_file|outfile',$value);

    if (!get_magic_quotes_gpc()) {   
        $value = mysql_real_escape_string($value);
    }
    return $value;
}

/**
 * 支持中文的json编码
 * @param  [type] $array [description]
 * @return [type]        [description]
 */
function jsonEncode($array) {
    arrayRecursive($array, 'urlencode', true);
    echo $json = json_encode($array);
    return urldecode($json);
}

/**
 * 使用特定function对数组中所有元素做处理
 * @param  [type]  $array              [description]
 * @param  [type]  $function           [description]
 * @param  boolean $apply_to_keys_also [description]
 * @return [type]                      [description]
 */
function arrayRecursive(&$array, $function, $apply_to_keys_also = false)  {
    foreach ($array as $key => $value) {
        if (is_array($value)) {
            arrayRecursive($array[$key], $function, $apply_to_keys_also);
        } else {
            $array[$key] = $function($value);
        }
 
        if ($apply_to_keys_also && is_string($key)) {
            $new_key = $function($key);
            if ($new_key != $key) {
                $array[$new_key] = $array[$key];
                unset($array[$key]);
            }
        }
    }
}

/**
 * 操作session 的快捷方法
 * @return [type] [description]
 */
function session($k="",$v="") {
    if(empty($v) && $v !== null) {
        return \IPHP\Core\Session::get($k);
    } else {
        \IPHP\Core\Session::set($k,$v);
    }
}